'use strict';

const { Controller } = require('egg');
const fs = require("fs")
const path = require("path")
const svg = require("svg-captcha")
class UserController extends Controller {
    async userinfo() {
        //判断用户是否登录和失效
        let res = await this.ctx.service.user.isLogin()
        if (res) {
            let uid = this.ctx.session.uid
            let sql1 = `select email,nickname,img from user where uid=${uid}`
            let res2 = await this.ctx.app.mysql.query(sql1)
            this.ctx.body = { code: 2000, info: res2[0] }
        }
        else {
            this.ctx.body = { code: 4000, info: "请重新登录" }
        }


    }

    async verif() {
        let { data, text } = svg.create({
            size: 4,
            fontSize: 50,
            width: 100,
            height: 40,
            background: '#cc9966'
        })

        this.ctx.session.verif1 = text//"asd123"
        this.ctx.body = { code: 2006, info: data }
    }
    async login() {
        const { ctx } = this;
        let { email, pwd, verif } = this.ctx.request.body
        let verif1 = this.ctx.session.verif1
        if (verif != verif1) {
            ctx.body = { code: 4007, info: "验证码错误" }
            return
        }
        let sql1 = `select * from user where email="${email}"`
        let res1 = await this.ctx.app.mysql.query(sql1)
        if (!res1[0]) {
            ctx.body = { code: 4004, info: "邮箱没有注册" }
            return
        }
        let sql2 = `select * from user where email="${email}" and pwd="${pwd}"`
        console.log(sql2)
        let res2 = await this.ctx.app.mysql.query(sql2)
        if (!res2[0]) {
            ctx.body = { code: 4005, info: "密码错误" }
            return
        }
        this.ctx.session.uid = res2[0].uid//有有效时期
        ctx.body = { code: 2005, info: "登录成功" }

    }
    async register() {
        const { ctx } = this;
        console.log(this.ctx.request.body, this.ctx.request.files)
        let { email, pwd, nickname } = this.ctx.request.body
        let f = this.ctx.request.files[0]
        if (!f) {
            ctx.body = { code: 4002, info: "头像未上传" }
            //或者把头像设置为默认的路径
            return
        }
        let sql1 = `select * from user where email="${email}"`
        let res1 = await this.ctx.app.mysql.query(sql1)
        if (res1[0]) {
            ctx.body = { code: 4001, info: "邮箱已注册" }
            return
        }

        let oldpath = f.filepath
        let newpath = __dirname + "/../public/upload/" + path.basename(oldpath)
        fs.copyFileSync(oldpath, newpath)
        let img = "/upload/" + path.basename(oldpath)
        let sql2 = `insert into user (email,pwd,nickname,img) values ("${email}","${pwd}","${nickname}","${img}")`
        this.ctx.app.mysql.query(sql2)
        this.ctx.body = { code: 2000, info: "注册成功" }
    }
}
module.exports = UserController;
